﻿@model Cxuu.Models.EditArticleAndContent
<div class="content-top-nav">
    <div class="layui-row">
        <div class="layui-col-md11">
            <h3 style="color:#444">
                <i class="layui-icon layui-icon-home"></i>
                内容编辑
            </h3>
        </div>
        <div class="layui-col-md1" style="text-align:right;">
            <button class="layui-btn layui-btn-sm" onclick="loadMain('/Admin/Content/')">返回列表</button>
        </div>
    </div>
    <hr>
</div>

<div class="layui-fluid" style="margin-bottom:50px;">
    <div class="layui-form">
        <form class="layui-form" action="" lay-filter="FormEdit" enctype="multipart/form-data">
            <div class="layui-form-item">
                <label asp-for="Cid" class="layui-form-label required"></label>
                <div class="layui-input-inline">
                    <select asp-for="Cid" asp-items="ViewBag.articleCateData"></select>
                </div>
            </div>
            <div class="layui-form-item">
                <label asp-for="Title" class="layui-form-label required"></label>
                <div class="layui-input-block">
                    <input type="text" asp-for="Title" lay-verify="required" lay-reqtext="标题不能为空" placeholder="请输入标题" value="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label asp-for="Content" class="layui-form-label"></label>
                <div class="layui-input-block">
                    <textarea id="contentEdit" name="Content" class="layui-textarea" placeholder="请输入内容"></textarea>
                </div>
            </div>
            @if (CheckExt.AuthView(ViewBag.sr, "content_att"))
            {
                <div class="layui-form-item">
                    <label class="layui-form-label required">位置属性</label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="AttA" value="1" title="头条">
                        <input type="checkbox" name="AttB" value="1" title="小头条">
                        <span id="lunhuantu"><input type="checkbox" name="AttC" value="1" title="图片轮换"></span>
                    </div>
                </div>
            }

            <div class="layui-form-item">
                <label class="layui-form-label required">附件</label>
                <div class="layui-input-block">
                    <div id="attval" class="cxuu_attmentupload"></div>
                    @if (CheckExt.AuthView(ViewBag.sr, "upload_upload"))
                    {
                        <input type="hidden" asp-for="Attments" value="" class="layui-input" id="Att">
                        <button type="button" class="layui-btn" id="attmentsUpload">
                            <i class="layui-icon ">&#xe608;</i>上传附件
                        </button>
                        <tip>支持多个附件上传，单个附件不超过 @ViewBag.fileSize KB！ 支持格式：@ViewBag.fileExts </tip>
                    }
                </div>
            </div>


            <div class="layui-form-item">
                <label asp-for="Examine" class="layui-form-label required"></label>
                <div class="layui-input-inline">
                    <input type="text" asp-for="Examine" lay-verify="required" lay-reqtext="发布人不能为空" placeholder="请输入发布人" value="" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label asp-for="Img" class="layui-form-label required"></label>
                <div class="layui-input-block">
                    <input type="text" id="imageval" asp-for="Img" value="" class="layui-input">
                    <!-- <button type="button" class="layui-btn" id="thumimg">
                      <i class="layui-icon">&#xe67c;</i>上传图片
                    </button> -->
                    <button type="button" class="layui-btn" id="getimage" onclick="getFirstImg()">
                        <i class="layui-icon">&#xe60d;</i>获取内容第一张图
                    </button>
                </div>
            </div>

            <div class="layui-form-item">
                <label asp-for="Status" class="layui-form-label">状态</label>
                <div class="layui-input-inline">
                    @if (CheckExt.AuthView(ViewBag.sr, "content_status"))
                    {
                        <input asp-for="Status" type="radio" value="1" title="发布" checked>
                    }
                    <input asp-for="Status" type="radio" value="0" title="草稿">
                    <input asp-for="Id" type="hidden">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="saveBtn" id="saveBtn">保存</button>
                </div>
            </div>
        </form>
    </div>
</div>
<script type="text/javascript" src="~/lib/tinymce/tinymce.min.js?v=5.82"></script>
<script>
    layui.use(['form', 'table', 'upload','jquery', 'element'], function () {
        var form = layui.form, layer = layui.layer, $ = layui.jquery,upload = layui.upload, element = layui.element;
        tinymce.init({
            selector: '#contentEdit',
            language: 'zh_CN',
            relative_urls: false,
            remove_script_host: true,
            plugins: 'print preview searchreplace autolink directionality visualblocks visualchars image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autoresize  axupimgs',
            toolbar: 'code | undo redo restoredraft | cut copy paste | forecolor bold italic underline link | alignleft aligncenter alignright alignjustify outdent indent | fontselect fontsizeselect | table image charmap emoticons insertdatetime preview |  axupimgs',
            autosave_interval: "20s",//自动存稿时间
            //font_formats: '微软雅黑=Microsoft YaHei,sans-serif;仿宋_GB2312=仿宋_GB2312,Microsoft YaHei,sans-serif;宋体=宋体;仿宋=仿宋;黑体=黑体',
            height: 650, //编辑器高度
            min_height: 400,
            draggable_modal: true,
            images_upload_base_path: '/',
            images_reuse_filename: true,
            images_upload_handler: function (blobInfo, succFun, failFun) {
                var xhr, formData;
                var file = blobInfo.blob();//转化为易于理解的file对象
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', '/Admin/Upload/Upload?type=Tinymce&source=Content&uid=@ViewBag.uid');
                xhr.onload = function () {
                    var json;
                    if (xhr.status != 200) {
                        failFun('HTTP Error: ' + xhr.status);
                        return;
                    }
                    json = JSON.parse(xhr.responseText);
                    if (!json || typeof json.location != 'string') {
                        failFun('Invalid JSON: ' + xhr.responseText);
                        return;
                    }
                    succFun(json.location);
                };
                formData = new FormData();
                formData.append('file', file, file.name);
                console.log(xhr);
                xhr.send(formData);
            }
        });

        form.render();

        var editId = @ViewBag.id+1;
        //console.log(editId);
        if (editId > 1) {
            $.getJSON("/Admin/Content/AddOrEdit?id=@ViewBag.id&edit=1", function (res) {
                if (res.status == 1) {
                    form.val('FormEdit', {
                        Cid: res.data.cid,
                        Content: res.data.content,
                        Examine: res.data.examine,
                        Attments: res.data.attments,
                        Img: res.data.img,
                        Id: res.data.id,
                        Status: res.data.status,
                        AttA: res.data.attA,
                        AttB: res.data.attB,
                        AttC: res.data.attC,
                        Time: res.data.time,
                        Title: res.data.title,
                    });
                    if (res.data.status)
                        $('input[name="Status"][value="1"]').prop('checked', 'checked');
                    else
                        $('input[name="Status"][value="0"]').prop('checked', 'checked');
                    form.render('radio');

                    if (res.data.attA ==1)
                        $('input[name="AttA"]').prop('checked', 'checked');
                    if (res.data.attB == 1)
                        $('input[name="AttB"]').prop('checked', 'checked');
                    if (res.data.attC == 1)
                        $('input[name="AttC"]').prop('checked', 'checked');
                    form.render('checkbox');

                    $.each(res.attments, function (index, value) {
                        $('#attval').append('<span id="attidd' + value.id + '" class="layui-badge layui-bg-blue"> ID：' + value.id + ' 文件名：' + value.filename + ' <a href="javascript:;" onclick="attColse(' + value.id + ')" ><i class="layui-icon layui-icon-close"></i></a></span>');
                    });
                }
                //console.log("json", res+"abc");

                //如果没有提取缩略图，就不能选择 轮换图
                var imageval = $('#imageval').val();
                if (imageval.length < 1) {
                    $('#lunhuantu').hide();
                } else {
                    $('#lunhuantu').show();
                }
            })
        } else {
            form.val('FormEdit', {
                Cid: @ViewBag.cid,
            });
            $('input[name="Status"][value="true"]').prop('checked', 'checked');
            form.render('radio');
        }
        //检测缩略图，显示隐藏
        $('#imageval').bind('input propertychange', function () {
            if ($(this).val().length) {
                $('#lunhuantu').show();
            } else {
                $('#lunhuantu').hide();
            }

        });

        var uploadInst = upload.render({
            elem: '#attmentsUpload'
            , url: '/Admin/Upload/Upload?type=layui&source=Content&uid=@ViewBag.uid'
            , before: function (obj) {
                element.progress('upload-att', '0%'); //进度条复位
                layer.msg('上传中', { icon: 16, time: 0 });
            }
            , done: function (res) {
                if (res.status == 1) {
                    $('#attval').append('<span id="attidd' + res.pkey + '" class="layui-badge layui-bg-blue"> ID：' + res.pkey + ' 文件名：' + res.data.filename + ' <a href="javascript:;" onclick="attColse(' + res.pkey + ')" ><i class="layui-icon layui-icon-close"></i></a></span>');
                    var input = $("#Att").val();
                    if (input != "" && input != undefined) {
                        $("#Att").val($("#Att").val() + "," + res.pkey);
                    } else {
                        $('#Att').val(res.pkey);
                    }
                    // console.log(res);
                    //res.result[0].src + res.result[0].suffix + res.result[0].size
                    layer.msg(res.info);
                } else {
                    layer.msg("上传失败！");
                }
            }
            //进度条
            , progress: function (n, elem, e) {
                element.progress('upload-att', n + '%');
                if (n == 100) {
                    layer.msg('上传完毕', { icon: 1 });
                }
            }
        });

        var dataPost = function (url, data) {
            console.log("json", data);
            $.post(url, data, function (res) {
                if (res.status == 1) {
                    layer.msg(res.msg, { icon: 1, time: 1000 }, function () {
                        loadMain('/Admin/Content/Index?cid=' + res.cid);
                    });
                } else
                    layer.msg(res.msg, { icon: 2, anim: 6, time: 5000 });
            });
        }

        //监听提交
        //form.on('submit(saveBtn)', function (data) {  form.val('FormEdit')
        $('#saveBtn').click(function () {
            //var field = $("form").serializeArray(); //输出数组
           var field = form.val('FormEdit');
            if (editId == 1) {
                var post = {
                    Cid: field.Cid,
                    Title: field.Title,
                    Examine: field.Examine,
                    Attments: field.Attments,
                    Img: field.Img,
                    Content: tinyMCE.editors[0].getContent(),
                    Status: field.Status,
                    AttA: field.AttA,
                    AttB: field.AttB,
                    AttC: field.AttC
                };
                dataPost('/Admin/Content/CreatePost', post);
            }
            else {
                var postEdit = {
                    Id: field.Id,
                    Cid: field.Cid,
                    Title: field.Title,
                    Examine: field.Examine,
                    Attments: field.Attments,
                    Img: field.Img,
                    Content: tinyMCE.editors[0].getContent(),
                    Status: field.Status,
                    AttA: field.AttA == 1 ? 1 : 0,
                    AttB: field.AttB == 1 ? 1 : 0,
                    AttC: field.AttC == 1 ? 1 : 0
                };
                dataPost('/Admin/Content/EditPost', postEdit);
            }
            return false;
        });
    });

    //获取编辑器内容的第一张图片
    function getFirstImg() {
        var content = tinyMCE.editors[0].getContent();
        var getval = $(content).find("img").eq(0).attr("src");
        if (getval.length > 0) {
            $('#imageval').val(getval);
            $('#lunhuantu').show(); //如果有内容，显示轮换选择框
        }
    }

    function attColse(id) {
        layer.confirm('真的删除这个附件吗？', { icon: 3, title: '警告' }, function (index) {
            $.post('/Admin/Attment/Delete', { id: id }, function (res) {
                if (res.status == 1) {
                    layer.msg("附件: " + res.msg);
                    $('#attidd' + id).remove();
                    var input = $("#Att").val();
                    var newarr = input.split(",");
                    newarr.splice($.inArray("" + id + "", newarr), 1);
                    $('#Att').val(newarr);
                } else {
                    layer.msg("附件: " + res.msg + "请查看是否有删除附件权限");
                }
            });
            layer.close(index);
        });
    }

</script>